﻿<?php
defined('_ACCESS') or die( 'Direct Access to this location is not allowed.' );
defined('_LOCATION') or die( 'Direct Access to this location is not allowed.' );
//session_start();
global $db, $item, $id, $option, $post; 			
global $NEW_users;

//user
$NEW_users=new stdClass();
$NEW_users->id=0;
$NEW_users->name='';
$NEW_users->username='';
$NEW_users->password='';
$NEW_users->account_type=0;
$NEW_users->gender='';
$NEW_users->begtime=date('H:i:s d.m.Y ');	
$NEW_users->endtime=date('H:i:s d.m.Y ');	
$NEW_users->filial_link=0;
$NEW_users->lang='RU';


//product
$NEW_prod=new stdClass();
$NEW_prod->id = 0;
$NEW_prod->type_id = 0;
$NEW_prod->data=array();




/*
define('WWW_TODAY', 'Today');
define('WWW_MINUS_1_DAY', '-1 day');
define('WWW_MINUS_2_DAYS', '-2 days');
define('WWW_MINUS_3_DAYS', '-3 days');
*/




//SETS
$Lang_Arr = array("EN" => "EN", "RU" => "RU", "DE" => "DE");
$Days_Arr = array("now" => WWW_TODAY, "-1" => WWW_MINUS_1_DAY, "-2" => WWW_MINUS_2_DAYS, "-3" => WWW_MINUS_3_DAYS);




/*================================================================================================*/
//option
//--new
//--edit
//--del

//item
//--news	   -		
//--docs    -
//--reports -
//--users

//id

//data

//access
//--public
//--register
//--admin

/*
echo '<br/><b>$item::'.$item.'</b>';
echo '<br/><b>$id::'.$id.'</b>';
echo '<br/><b>$option::'.$option.'</b>';
echo '<br/><b>$post::'.$post.'</b><br/>'; 
*/

function getRequest_var($vVal)
{
	$vVal = (string) $vVal;	
	if (isset($_REQUEST[$vVal])) 
    {
    	return $_REQUEST[$vVal];
    } 
    else if (isset($_POST[$vVal])) 
    {
    	return $_POST[$vVal];
    } 
    else return null;    
}
/*================================================================================================*/
if (!isset($item)) 
{
	$data = getRequest_var('data');		
	$data_id = getRequest_var('data_id');	
	$param_graph = getRequest_var('param_graph');
	$item = getRequest_var('item');
	$id = getRequest_var('id');
	$option = getRequest_var('option');
/////////////////////////////////////////
    if (isset($_REQUEST['start'])) 
    {
    	$start=$_REQUEST['start'];
    	if ($start==='') $start=0;
    } 
    else $start=0; 
/////////////////////////////////////////    
    if (isset($_REQUEST['post'])) 
    {
    	$post=$_REQUEST['post'];
    } 
    else $post=0;   
}
/*================================================================================================*/
function logOut()
{
	global $db;	
	$db->clearSettings();	
}
/*================================================================================================*/
function setLang()
{
	global $db, $id;	
	//if(!$id)$id='EN';	
	$Lang = $db->getSetting('Lang');
	if ($Lang and $db->getSetting('access'))
	{		
		$user_id = $db->getSetting('User_id');	
		$sql = "UPDATE users SET lang = '$id' WHERE id=$user_id LIMIT 1";
		//echo '<br/><b>$sql::'.$sql.'</b><br/>';
		$res=$db->query($sql);		
		$n=mysql_affected_rows();
		if($n>0)
		{
			$db->setSetting('Lang', $id);
		}		
	}
	else $db->setSetting('Lang', $id);
	
}
/*================================================================================================*/
function setViewDate()
{
	global $db, $id;	
	$is_day_set = false;
		
	//first day
	$day1 = getdate(strtotime ("-1 day"));
	$is_day_set = false;	
	while( ! $is_day_set)
	{
		if (($day1["wday"] == 0) || ($day1["wday"] == 6)) $day1 = getdate(strtotime ("-1 day", $day1["0"]));
		else $is_day_set = true;
	}	
	//second day
	$day2 = getdate(strtotime ("-1 day", $day1["0"]));
	$is_day_set = false;	
	while( ! $is_day_set)
	{
		if (($day2["wday"] == 0) || ($day2["wday"] == 6)) $day2 = getdate(strtotime ("-1 day", $day2["0"]));
		else $is_day_set = true;		
	}
	//third day
	$day3 = getdate(strtotime ("-1 day", $day2["0"]));
	$is_day_set = false;	
	while( ! $is_day_set)
	{
		if (($day3["wday"] == 0) || ($day3["wday"] == 6)) $day3 = getdate(strtotime ("-1 day", $day3["0"]));
		else $is_day_set = true;
	}
	
	switch ($id)
	{		
		case "now":
			$db->setSetting('ViewDate', date("d.m.Y"));			
			
			break;
		case "-1":
			$db->setSetting('ViewDate', date("d.m.Y", $day1["0"]));
			break;
		case "-2":
			$db->setSetting('ViewDate', date("d.m.Y", $day2["0"]));				
			break;
		case "-3":
			$db->setSetting('ViewDate', date("d.m.Y", $day3["0"]));
			break;		
	}
	$db->setSetting('ViewDateRel', $id);	
}
/*================================================================================================*/
function setProd()
{
	global $db, $id;	
	$db->setSetting('Prod_id', $id);
}
/*================================================================================================*/
function flipdate($dt, $seperator_in = '-', $seperator_out = '-')
{
	return implode($seperator_out, array_reverse(explode($seperator_in, $dt)));
}
/*================================================================================================*/
function DatesOut()
{
	global $db, $Days_Arr;	
?>
<div id=dates>    
<?php
	foreach ($Days_Arr as $key => $value)
	{
?>
	<div <?php if($db->getSetting('ViewDateRel') == $key) echo " class=choosed>"."$value";else echo " class=unchoosed>"."<a href=".'"'."index.php?item=date&amp;id=$key".'">'."$value".'</a>';?></div>
<?php
	}
?>	
        <input type="hidden" name=in_day value="" />
		
	<form name=my_data_form id=my_data_form action="">
		
		
		
		<!--div id=date_cont name=date_cont class=unchoosed-->
			<input align="top" type="text" size="10" readonly="<?php echo $db->getSetting('ViewDate');?>" onchange='setDate();' class="date" name=my_date1 id=my_date1 value="<?php echo $db->getSetting('ViewDate');?>" />
		<!--/div-->	
		<script language="JAVASCRIPT" type="text/javascript">
			//var my_date1 = new calendar_create( document.forms['my_data_form'].elements['my_date1'] );
			var calendar = new calendar_create( document.my_data_form.my_date1 );
			
		</script>
		<!--div class=unchoosed-->
			<a  href='javascript:calendar.popup();'>
		    	<img align="top" src='admin/js/images/calendar.gif' alt="" />
		    </a>
	    <!--/div-->
	 </form>

</div>
<?php
}
/*================================================================================================*/
function LangsOut()
{
	global $db, $Lang_Arr;		
?><div id=lang><?php
	foreach ($Lang_Arr as $key => $value)
	{
?> <div <?php		
		if($db->getSetting('Lang') == $key)
		{
			echo " class=choosed>";	
			echo ""."$value";		
		}
		else 
		{
			echo " class=unchoosed>";
			echo "<a href=".'"'."index.php?item=lang&amp;id=$key".'">';
			echo "$value";
			echo '</a>';			
		}
?></div>	
<?php
	}
?>
<div class="breakline"></div>
</div> 
<?php
}
/*================================================================================================*/
function menuOut()
{
	global $db, $item, $id, $option;
?>
<div id=sidebar>
<?php
if ($db->getSetting('access'))
{	
	$Lang = $db->getSetting('Lang');
	$Filial_id = $db->getSetting('Filial_id');
	$res=$db->query("SELECT $Lang AS trans, prodlist.id
					FROM         translation INNER JOIN	prodlist 
													ON translation.id = prodList.translation_link 
											 INNER JOIN  filialandprod 
													ON prodlist.id = filialandprod.prod_link
					WHERE     (filialandprod.filial_link = $Filial_id) ORDER BY prodlist.id");
?><ul><?php	
	while($cur_product = $db->fetchObject($res))
	{
		if($db->getSetting('Prod_id') == $cur_product->id)
		{
			echo "<li class=choosed>".$cur_product->trans;		
		}
		else
		{
?><li class=unchoosed ><a href="index.php<?php echo "?id=".$cur_product->id;?>&amp;item=prod"><?php echo $cur_product->trans;?></a>
<?php 
		}
	?></li><?php 
	}?></ul><?php
}	
?>
</div>
<?php
}
/*================================================================================================*/
/*================================================================================================*/
/*================================================================================================*/
/*================================================================================================*/
function graphOut()
{
    //param_graph
    
    global $db, $item, $id, $option, $param_graph;
    $Prod_id = $db->getSetting('Prod_id');     
    $Lang = $db->getSetting('Lang');
    
    
    
    /*$res=$db->query("SELECT $Lang AS trans
                        FROM Translation INNER JOIN  ParamList 
                                                      ON Translation.id = ParamList.translation_link 
                                            INNER JOIN ProdAndParam 
                                                      ON ParamList.id = ProdAndParam.param_link
                        WHERE     (ProdAndParam.prod_link = $Prod_id) 
                        ORDER BY ProdAndParam.order LIMIT 1");
    while($cur_param = $db->fetchObject($res))
    {     
         $params[$cur_param->param_link] = $cur_param;          
         $params_names[$cur_param->param_link] = $cur_param->trans;
    }
    
    */
    
    
    /*
    $res=$db->query("SELECT Data.val, Data.id
                                  FROM TypeList INNER JOIN
                                            Data INNER JOIN
                                    ProdList ON Data.prod_link = ProdList.id INNER JOIN
                                    ParamList ON Data.param_link = ParamList.id ON TypeList.id = Data.prod_type_link 
                   WHERE     (Data.user_link = $User_id) 
                                  AND (Data.prod_link = $Prod_id) 
                                  AND (Data.prod_type_link = $type_key) 
                                  AND (Data.modif_date like '".flipDate($db->getSetting('ViewDate'), '.')."%') 
                                  AND (Data.param_link = $param_key) LIMIT 1");
    */
    
    $res=$db->query("SELECT Data.val, Data.id, DAY(Data.modif_date) AS md, Data.type_of_val
                                  FROM TypeList INNER JOIN
                                            Data INNER JOIN
                                    ProdList ON Data.prod_link = ProdList.id INNER JOIN
                                    ParamList ON Data.param_link = ParamList.id ON TypeList.id = Data.prod_type_link 
                   WHERE      (Data.prod_link = $Prod_id)
                                  AND (Data.param_link = $param_graph) 
                   ORDER BY Data.modif_date");
    
    $datax = array_fill(0, 30, 0);     
    for ($i=0; $i<count($datax); $i++) 
    {
        $datax[$i] = $i;
    }     
    //$datax = array(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29);
    
    $data = array_fill(0, 30, 0);     
    while($cur_param_value = $db->fetchObject($res))
    {                    
         $data[$cur_param_value->md] = (int) $cur_param_value->val;          
         
         //substr($cur_param_value->modif_date, 8, 2);          
         //$param_values[$cur_param_value->value_link] = $cur_param_value->trans;                         
    }
    print_r($data);
    
    
    //$data1 = array(30,25,33,25, 79, 89, 23, 63, 77, 84, 35, 31, 98, 33, 10, 20, 30, 40, 50, 60, 70, 80, 90, 110, 50, 30, 20, 27, 45, 32);          
    //$data2 = array(50, 65, 33,25, 79, 89, 23, 63, 77, 50, 35, 31, 98, 33, 60, 20, 30, 40, 50, 60, 70, 80, 90, 10, 50, 30, 20, 27, 45, 32);     
    
    
    
    // Create the graph. These two calls are always required
    $graph = new Graph(650, 450, "auto");
    $graph->SetScale("textlin");
    //$graph->SetScale("textlog");
    
    $graph->img->SetMargin(40,110,20,40);
    $graph->SetShadow();
    
    $graph->ygrid->Show(true,true);
    $graph->xgrid->Show(true,false);     
    
    // Create the linear plot
    $lineplot1 = new LinePlot($data, $datax);
    $lineplot1->SetColor("blue");     
    $lineplot1->value->SetColor("red");     
    //$lineplot1->value->SetFont(FF_FONT1,FS_BOLD);
    $lineplot1->value->Show();

    
    //$lineplot2 = new LinePlot($data2, $datax);
    //$lineplot2->SetColor("green");
    //$lineplot->SetFillGradient('yellow@0.4','red@0.4');
    
    // Add the plot to the graph
    $graph->Add($lineplot1);
    //$graph->Add($lineplot2);
    
    $graph->title->SetFont(FF_VERDANA);
    $graph->title->Set("Заголовок - Пример2");
    
    $graph->xaxis->title->SetFont(FF_VERDANA);
    $graph->xaxis->title->Set("Дни");
    
    $graph->yaxis->title->SetFont(FF_VERDANA);
    $graph->yaxis->title->Set("Данные");
    $graph->yaxis->SetColor("blue");
    
    $lineplot1->SetLegend("Легенда 1");
    //$lineplot2->SetLegend("Легенда 2");     
    
    $graph->legend->SetFont(FF_VERDANA);
    $graph->legend->Pos(0.05,0.5,"right","center");
    
    $graph->Stroke("mygif2.gif");
    
    print_r($data);     
}

}/*================================================================================================*/
function loginFromOut()
{
	global $db, $item, $id, $option;
?>
<div id="login">
<?php
if ($db->getSetting('access'))
{	
?>
	<?php echo WWW_HELLO.", ".$db->getSetting('uname');?>
	<a href="index.php?item=logout" id=readmore>
		<img alt="" src="images/li.gif" height="9" width="15" border="0" /> <?php echo WWW_LOGOUT_CAPTION;?>
	</a>		   
<?php
}
	else
{
	echo WWW_LOGIN_FORM_CAPTION;?>
	<form action="index.php" method="post" name="login" >
		<?php echo WWW_USER;?>
		<input name="usrname" type="text" class="inputbox" size="15" />
		<?php echo WWW_PASSWORD;?>
		<input name="pass" type="password" class="inputbox" size="15" />
		<input type="hidden" name="item" value="login" />
		<input type="submit" name="submit" class="button" value="<?php echo WWW_LOGIN_FORM_SUBMIT_CAPTION;?>" />
	</form>
<?php
}	
?>
</div>
<?php
}
/*================================================================================================*/
function LeftRight($records,$start,$URL,$inpage) 
{
	$str='<table class="text">
					<tr>
						<th colspan="3">';	
	if ($start!=0)
	{
		$str.='<span class="pagenav"><a href="'.$URL.'"0><< Начало</a></span>&nbsp;';
		$str.='<span class="pagenav"><a href="'.$URL.($start-1).'>< Предыдущая</a></span>&nbsp;';
	}
	else $str.='<span class="pagenav"><< Начало</span>&nbsp;
				<span class="pagenav">< Предыдущая</span>&nbsp;';	
	if ($start==0) {$sstart=$start-0;$send=$start+10;}
	if ($start==1) {$sstart=$start-1;$send=$start+9;}
	if ($start==2) {$sstart=$start-2;$send=$start+8;}
	if ($start==3) {$sstart=$start-3;$send=$start+7;}
	if ($start==4) {$sstart=$start-4;$send=$start+6;}
	if ($start>=5) {$sstart=$start-5;$send=$start+5;}
	
	if ($send*$inpage>$records) $send=$records/$inpage;
	if ($sstart<0) $sstart=0;
	
	if ($records%$inpage==0) $add=0; else $add=1;
	for ($i=$sstart;$i<$send;$i++) 
	{
	    if ($i==$start) $str.='<span class=cur> <B>'.($i+1).'</B> </span>&nbsp;';
	    else $str.='<span class="pagenav"><a href='.$URL.($i).'>'.($i+1).'</a></span>&nbsp;';
	}
	
	if ($start+(1-$add)<intval($records/$inpage))
	{
	    $str.='<span class="pagenav"><a href="'.$URL.($start+1).'">Следующая ></a></span>&nbsp;';
	    $str.='<span class="pagenav"><a href="'.$URL.(intval($records/$inpage)-(1-$add)).'">Конец >></a></span>&nbsp;';
	}
	else $str.='<span class="pagenav">Следующая ></span>&nbsp;<span class="pagenav">Конец >></span>&nbsp;';
	$str.='				</th>
					</tr>
				</table>';
	return($str);
}
/*================================================================================================*/
function checkNconvValue($val)
{
	$str='';
	if (strtolower($val)==='null') 
	{
		$str=$val;
	}
	else 
	{
		$val=str_replace("'",'\'',$val);
		//$val=str_replace('"','\"',$val);
		//echo '<br/><b>$val::'.$val.'</b><br/>';
		$val=nl2br(strip_tags($val,'<a><b><i><u>'));
		$str="'".str_replace("\n",'',$val)."'";
	}
	return $str;
}
/*================================================================================================*/
function uNcheckNconvValue($val)
{
	//return str_replace("<br />", "\n", html_entity_decode($val,ENT_NOQUOTES));	
	//return html_entity_decode($val,ENT_NOQUOTES);
	$val=str_replace('\'',"'",$val);
	return strip_tags(html_entity_decode($val, ENT_NOQUOTES),'<a><b><i><u>');
}
/*================================================================================================*/


class PrintHTML
{
	/*================================================================================================*/
	function labelOut($label)
	{
		$label = (string) $label;
		echo "<label>$label</label>";	
	}	
	/*================================================================================================*/
	function editOut($editName = '', $editValue = '', $size = 0,  $className = '')
	{		
		if ($editName == '') return;
		$size = (int) $size;		
		echo '<input type="text" id="'.$editName.'" name="'.$editName.'"';
		if ($className !== '') echo ' class ="'.$className.'"';
		if ($size !== 0) echo ' size = "'.$size.'"';
		echo ' value="'.$editValue.'">';
	}
	/*================================================================================================*/
	function buttonOut($label, $type='button', $className = '',  $onclick='')
	{	
		echo'<input type="'.$type.'" value="'.$label.'"';
		if ($className !== '') echo ' class ="'.$className.'"';
		echo ' onclick="'.$onclick.'" />';		
	}	
	/*================================================================================================*/
	function listOut($listName='', $listOptions, $selectedInd)
	{	
		$listName = (string) $listName;
		if ($listName == '') return;
		echo('<select id="'.$listName.'" name="'.$listName.'">');
		if (is_array($listOptions))
		{
			foreach ($listOptions as $key => $value)
			{
				echo '<option value="'.$key.'"';
				if ($key == $selectedInd) 
				{
					echo " selected";				
				}				
				echo ">$value</option>";
			}		
		}		
		echo('</select>');
	}
	/*================================================================================================*/
	function hiddenOut($hiddenName, $hiddenValue = '')
	{		
		$hiddenName = (string) $hiddenName;
		if ($hiddenName == '') return;
		echo '<input type="hidden" id="'.$hiddenName.'" name="'.$hiddenName.'"';			
		echo ' value="'.$hiddenValue.'">';
	}	
	/*================================================================================================*/
	function labeledEditOut($label, $editName = '', $editValue = '', $size = 0, $className = '')
	{
		self::labelOut($label);		
		self::editOut($editName = '', $editValue = '', $size, $className = '');		
	}	
	/*================================================================================================*/
	function labeledListOut($label, $listName='', $listOptions, $selectedInd)
	{	
		self::labelOut($label);		
		self::listOut($listName='', $listOptions, $selectedInd);
	}	
}

/*================================================================================================*/
function doPost()
{
	global $NEW_prod, $post, $option, $db, $data, $data_id;
	if ($post==1)
	{	
		switch ($option)
		{
			case 'new':	
				//$db_obj=new DbConnector();										
				$sql = '';
				$sql1 = '';
				
				$user_id = $db->getSetting('User_id');
				$prod_id = $db->getSetting('Prod_id');
				$cur_date = $db->getSetting('ViewDate');
				$n = 0;
				
				
				foreach ($data as $type_key => $type_value)
				{	
					/*echo 'type_value-';
					print_r($type_value);
					echo ';';
					
					echo 'type_key-';
					print_r($type_key);
					echo ';';*/
					
					//echo '$data_id-';				
					//print_r($data_id);
					//echo ';';
					
					
					foreach ($type_value as $param_key => $param_value)
					{	
						if ($param_value != '')
						{
							$type_id = $type_key;
							$param_id = $param_key;	
							
							
							$s = "".$data_id[$type_id][$param_id];
							
							//$data_id[$type_id][$param_id] = (string) $data_id[$type_id][$param_id];
							//echo '<br/><b>$s::'.$s.'::</b><br/>';
							
							if ($s == "-1")
							{
								$sql = "INSERT INTO data (user_link, modif_date, val, prod_link, param_link, prod_type_link, target_date";
								$sql1 = "$user_id, '".flipdate($cur_date, '.', '-')."', '$param_value', $prod_id, $param_id, $type_id, '".flipdate($cur_date, '.', '-')."'";								
								$sql .= ") VALUES($sql1)";						
							}
							else 
							{						
								$sql = 'UPDATE data SET `val` = \''.$param_value.'\' WHERE `id` = '.$s." LIMIT 1";												
							}
							//echo '<br/><b>$sql::'.$sql.'</b><br/>';
							$res = $db->query($sql);
							$v = mysql_affected_rows();
							if($v <= 0) $v = 0;							
							$n = $n + $v;							
						}
					}
				}
				echo '<b>'.WWW_ADD_EDITED_OBJECTS.': ';
				if($n<=0) echo 0; else echo $n;
				echo '</b>';
				break;
		}
	}
}
/*================================================================================================*/
function reloadPage()
{
	global $db;
	echo "<script>";					
	echo "document.location.href='".$db->getSetting('_live_site')."index.php';</script>\n";	
}
/*================================================================================================*/
function mainFunc()
{
	global $db, $item, $id, $option, $post;
	global $data;
	
	
	switch (_LOCATION)	
	{
		case 'WWW':
			$location=$db->getSetting('_absolute_path');			

			switch ($item)
			{
				case 'lang':
					setLang();
					reloadPage();
					//exit();
					break;
					
				case 'date':
					setViewDate();
					reloadPage();
					//exit();
					break;
					
				case 'prod':
				
					if (isset($option) and $option!='' and $post==1)
					{						
						doPost();
					}
					else setProd();
					//
					//exit();
					break;
							
				case 'graph':
					
				
					include_once("jpggpraph/jpgraph.php");
					include_once("jpggpraph/jpgraph_log.php");					
					include_once("jpggpraph/jpgraph_line.php");					
					//include_once("jpggpraph/jpgraph_iconplot.php");	
					//include_once($location."includes/graph.php");
					graphOut();
					//
					//exit();
					break;
				
				case 'logout':
					logOut();
					reloadPage();
					//exit();
					break;
										
				case 'login':
					include_once($location."login.php");
					reloadPage();
					//exit();
					break;
			
				default:
					//require_once($location."main.php");
					break;
			}
			
		
			break;
			
			case 'ADMIN':
						
			if ( $access=='admin')
			{
				$location=$_absolute_path.'admin';
				switch ($item)
				{
					case 'news':
						include_once("$location/news.php");												
						//exit();						
						break;
						
					case 'docs':
						include_once("$location/docs.php");												
						//exit();						
						break;
						
					case 'reports':
						include_once("$location/reports.php");												
						//exit();							
						break;
						
					case 'users':
						include_once("$location/users.php");												
						exit();						
						break;
						
					case 'categories':
						include_once("$location/categories.php");												
						//exit();	
						break;
					case 'logout':
						logOut();
						echo "<script>";					
						echo "document.location.href='$_live_site"."index.php';</script>\n";
						exit();
						break;
				
					default:
						require_once("$location/main.php");						
						//exit();					
						break;
				}				
			}				
			break;
				
		default:
			break;
	}	
	
}
?>
